package com.scut.fy.gateway.service.impl;

import com.scut.fy.common.core.util.Assert;
import com.scut.fy.common.core.util.BeanUtils;
import com.scut.fy.gateway.fegin.FyAdminFeign;
import com.scut.fy.gateway.model.dto.SysUserDto;
import com.scut.fy.gateway.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author JY
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Qualifier("fyAdminFeignFallback")
    @Autowired
    private FyAdminFeign fyAdminFeign;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public SysUserDto findUserDtoByUserName(String userName) {
        Assert.notNull(userName, "用户名不能为空");
        // 先查redis里面有没有这个用户的数据
        SysUserDto userDto = new SysUserDto();
        userDto = BeanUtils.jsonToBean(
                redisTemplate.opsForValue().get("FY_GATEWAY_SYS_USER"+userName).toString(),
                SysUserDto.class);
        if (null == userDto) {
            // 如果是空，从feign接口查询
            userDto = BeanUtils.mapToBean(
                    fyAdminFeign.findUserByUserName(userName).getData(), SysUserDto.class);
            if (null != userDto) {
                // 查完后缓存到redis里面
                redisTemplate.opsForValue().set("FY_GATEWAY_SYS_USER"+userName, userDto, 60*30);
            }
        }
        return userDto;
    }

    @Override
    public SysUserDto findUserDtoByUserId(long userId) {
        SysUserDto userDto = new SysUserDto();
        // 先查redis里面有没有这个用户的数据
        userDto = BeanUtils.jsonToBean(
                redisTemplate.opsForValue().get("FY_GATEWAY_SYS_USER" + String.valueOf(userId)).toString(),
                SysUserDto.class);
        if (null == userDto) {
            // 如果是空，从feign接口查询
            userDto = BeanUtils.mapToBean(
                    fyAdminFeign.findUserByUserId(userId).getData(), SysUserDto.class);
            if (null != userDto) {
                // 查完后缓存到redis里面
                redisTemplate.opsForValue().set("FY_GATEWAY_SYS_USER" + String.valueOf(userId), userDto, 60*30);
            }
        }
        return userDto;
    }
}
